﻿using MyUtils;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using WebSite.Entity;
using WebSite.IDAL;
using WebSite.Models;

namespace WebSite.DAL
{
    public class RoleDAL : BaseDAL, IRole
    {
        public string getRoleName(string roleId)
        {
            string sql = "select role_name FROM fa_role where role_id = @0";
            return StringUtils.NullToBlank(getDBUtils().GetSingle(sql, roleId));
        }

        public List<RoleListVo> getRoleList()
        {
            string sql = "select * FROM fa_role";
            return getDBUtils().Query<RoleListVo>(sql);
        }


        public RoleVo getRoleVo(string roleId)
        {
            string sql = "select * FROM fa_role where role_id = @0";
            return getDBUtils().Single<RoleVo>(sql, roleId);
        }

        public bool addRole(FaRole entity, string menuStr)
        {
            if (entity.RoleId == null)
                entity.RoleAddtime = DateTime.Now;
            SqlTransaction tran = null;
            try
            {
                tran = getDBUtils().beginTransaction();
                getDBUtils().SaveOrUpdate(tran, entity);
                getDBUtils().Execute(tran, "delete from fa_role_module where role_id=@0", entity.RoleId);
                string[] menus = menuStr.Split(",".ToCharArray());
                foreach (string m in menus)
                {
                    getDBUtils().Execute(tran, "INSERT INTO fa_role_module ([role_id] ,[module_id]) VALUES (@0 ,@1)", entity.RoleId, m);
                }
                tran.Commit();
                return true;
            }
            catch (Exception e)
            {
                tran.Rollback();
                LogHelper.Error("添加角色失败", e);
                return false;
            }
            finally
            {
                getDBUtils().close(tran);
            }
        }

        public bool delRole(string roleId)
        {
            string sql = "delete FROM fa_role where role_id = @0";
            return getDBUtils().Execute(sql, roleId);
        }
    }
}